package com.laboratory.serviceprovide.setting.service.impl;

import com.Laboratory.setting.service._noticeService;
import com.Laboratory.workBench.pojo.notice;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.laboratory.serviceprovide.constant.constantArgs;
import com.laboratory.serviceprovide.workBench.mapper.noticeMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author acok
 * @description:TODO
 * @Date 2022/12/30 15:40
 * @Version 1.0
 */
@DubboService(interfaceClass = _noticeService.class,version = "1.0.0")
public class _noticeServiceImpl implements _noticeService {
    @Resource
    private noticeMapper noticeMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private void updateCache(int result){
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        if(result>0){
            if(ops.get(constantArgs.REDIS_NOTICES_KEY)!=null){
                ops.setIfPresent(constantArgs.REDIS_NOTICES_KEY,
                        JSON.toJSONString(noticeMapper.getAllNotices()),
                        15*60,
                        TimeUnit.SECONDS);
            }
        }
    }

    @Override
    public int createNotice(notice notice) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        if(ops.get(constantArgs.REDIS_NOTICES_KEY)!=null){
            List<notice> resultList= JSON.parseObject(ops.get(constantArgs.REDIS_NOTICES_KEY),new TypeReference<List<notice>>(){});
            assert resultList != null;
            resultList.add(0,notice);
            ops.set(constantArgs.REDIS_NOTICES_KEY, JSON.toJSONString(resultList), 15 * 60, TimeUnit.SECONDS);
        }
        return noticeMapper.createNotice(notice);
    }

    @Override
    public int updateNoticeById(notice notice) {
        int i = noticeMapper.updateNoticeById(notice);
        updateCache(i);
        return i;
    }

    @Override
    public int deleteNoticesByIds(String[] ids) {
        int i = noticeMapper.deleteNoticesByIds(ids);
        updateCache(i);
        return i;
    }

    @Override
    public List<notice> getNoticesByCondition(String createDate, String title) {
        String formatCreateDate=null;
        if (createDate.length()>0){
            formatCreateDate=createDate.substring(1,createDate.length()-1);
        }
        return noticeMapper.getNoticesByCondition(formatCreateDate, title);
    }
}
